package com.example.ai.page

import android.app.Activity
import android.content.Intent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.HorizontalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.example.ai.VideoChatActivity
import com.example.ai.model.data.ChatRoomData
import com.example.ai.model.viewmodel.MessageViewModel
import com.example.ai.view.MessageInput
import com.example.ai.view.MessageItem
import com.example.ai.view.TitleBarView

/**
 * Created by lijinxi on 2024/3/7.
 * @Description:
 */
@Composable
fun TextChatPage(viewModel: MessageViewModel) {
    val context = LocalContext.current
    val listState = rememberLazyListState()

    LaunchedEffect(key1 = viewModel.messages.size) {
        val index = viewModel.messages.size - 1
        if (index > 0) {
            listState.scrollToItem(index)
        }
    }

    Column(modifier = Modifier.fillMaxSize()) {
        TitleBarView(title = viewModel.chatRoomTitle(),
            onLeftClick = {
                (context as? Activity)?.finish()
            },
            onRightClick = {
            })

        Box(modifier = Modifier.weight(1f)) {
            LazyColumn(state = listState) {
                itemsIndexed(viewModel.messages) { index, item ->
                    MessageItem(messageData = item, index = index, loadAudioUrl = { _index ->
                        viewModel.fetchVoice(_index)
                    })
                }
            }
        }
        HorizontalDivider(modifier = Modifier.padding(top = 16.dp), color = Color.Transparent)
        Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.BottomCenter) {
            MessageInput(
                onSendMessage = { text ->
                    viewModel.sendMessage(text)
                },
                onPhoneCall = {
                    //启动新的Activity, 进行实时交互/
                    context.startActivity(
                        Intent(
                            context,
                            VideoChatActivity::class.java
                        ).apply {
                            putExtra("title", viewModel.chatRoomTitle())
                        })
                }
            )
        }
    }

    BackHandler {
        viewModel.close()
        (context as? Activity)?.finish()
    }
}